package yxy.cherry.paycenter.channelmodule.sdk_huawei_quick;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.joda.time.DateTime;
import yxy.apple.logger.Logger;
import yxy.apple.util.MathUtil;
import yxy.apple.util.SdkUtil;
import yxy.cherry.data.bean.charge;
import yxy.cherry.paycenter.channelmodule.PayMoudle_channel;
import yxy.cherry.paycenter.database.db.orders;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.channel.SdkChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannel;
import yxy.game.pm2.bean.db.sdk.SDK_UnionChannelDAO;
import yxy.game.pm2.bean.module.OrderInfoModule;
import yxy.game.pm2.bean.order.OrderInfo;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

public class PayMoudle_huawei_quick extends PayMoudle_channel {
	static final Logger logger = Logger.create(PayMoudle_huawei_quick.class);

	@Override
	public String getChannel() {
		return SdkChannel.sdk_huawei_quick;
	}

	@Override
	public JSONObject dealPay(JSONObject infoobj) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public JSONObject createOrderInfo(JSONObject infoobj, orders o) throws Exception{
		JSONObject extObj = JSONObject.parseObject(infoobj.getString("ext")); //扩展参数
		String appId = extObj.getString("appId");

		//读取渠道配置
		SDK_UnionChannel unionChannel = SDK_UnionChannelDAO.getByAppId(o.getChannel(), appId);

		JSONObject json = new JSONObject();
//		String orderNo, String ProductName, double Price, String ProductId
		json.put("orderNo", o.getMyorderid());
		json.put("ProductName", o.getGoodsname());
		json.put("ProductId", o.getGoodsid());
		json.put("Price", o.getGoodsprice());

		//生成sign
		Map<String, String> params = new HashMap<>();
		params.put("merchantId", unionChannel.getAppKey());
		params.put("applicationID", unionChannel.getAppId());
		params.put("amount", MathUtil.str_divide(String.valueOf(o.getGoodsprice()), "100", 2)); //分 转 元
		params.put("productName", o.getGoodsname());
		params.put("productDesc", o.getGoodsname());
		params.put("requestId", o.getMyorderid()); //商户订单号
		params.put("sdkChannel", "3"); //渠道信息，快游戏请设置为3。
		params.put("urlver", "2"); //支付结果回调版本。请CP关注，该值可以不传，如果传值则固定值传2，如果不传2会导致支付不成功。
		logger.info("PayMoudle_huawei_quick:createOrderInfo : %s", JSON.toJSON(params));
		String signContent = SdkUtil.mapToContent(params, false);
		String sign = rsaSign(signContent, unionChannel.getPrivateKey());
		params.put("sign", sign);
		params.put("extReserved", o.getPlayercode()); //透传参数，传用户code
		json.put("orderInfo", params);
		logger.info("PayMoudle_huawei_quick:createOrderInfo : %s", JSON.toJSON(json));
		
		return json;
	}

	public orders createOrderHUAWEIQUICK(int dataid, String playercode, int serverid, int acttype) {
		orders o = createOrder(getChannel(), dataid, acttype, playercode, serverid);
		addOrder(o);
		return o;
	}
	
	/**
	 * 创建 OrderInfo
	 * @param o
	 * @param curs
	 * @param c
	 * @param payamount
	 */
	public void createOrderInfoModule(orders o, ArrayList<Currency> curs, charge c, int payamount) {
		createOrderInfoModule(o, curs, c.getVipexp(), payamount);
	}
	
	/**
	 * 
	 * @param o
	 * @param curs
	 * @param vipexp
	 * @return
	 */
	public void createOrderInfoModule(orders o, ArrayList<Currency> curs, int vipexp, int payamount) {
		OrderInfo oi = OrderInfoModule.createOrderInfo(o.getGoodsid(), o.getChannel(), o.getMyorderid(), new DateTime(o.getCreatetime().getTime()), 
				OrderInfoModule.orderinforuning, o.getPlatorderid(), o.getActtype(), o.getPlayercode(), curs, 
				o.getServerid(), DateTime.now(), vipexp, payamount, o.getGoodsprice());
		logger.info("createOrderInfoModule %s", JSON.toJSONString(oi));
		OrderInfo.set(o.getPlayercode(), oi);
	}

	/**
	 * 使用开发者联盟网站分配的支付私钥对支付信息进行签名
	 * 强烈建议在商户服务端做签名处理，且私钥存储在服务端，防止信息泄露
	 * CP通过服务器获取服务器端的签名之后，再进行支付请求
	 * @param content
	 * @return
	 */
	public static String rsaSign(String content, String privateKey) {
		if (null == content) {
			return null;
		}
		//使用加密算法规则
		String SIGN_ALGORITHMS = "SHA256WithRSA";
		String charset = "UTF-8";
		try {
			//Base64请采用服务器端标准的Base64算法库。
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
			KeyFactory keyf = KeyFactory.getInstance("RSA");
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);
			java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
			signature.initSign(priKey);
			signature.update(content.getBytes(charset));
			byte[] signed = signature.sign();
			//Base64请采用服务器端标准的Base64算法库。
			return Base64.encodeBase64String (signed);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		}
		return null;
	}

}
